
import 'package:flutter/material.dart';
import 'package:nft_shop/my/model/models.dart';
import 'package:nft_shop/net/service_repository.dart';
import 'package:nft_shop/res/constant.dart';
import 'package:nft_shop/res/global.dart';
import 'package:nft_shop/util/route_observer.dart';
import 'package:nft_shop/widgets/load_image.dart';
import 'package:nft_shop/widgets/status_view.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class ReviewListPage extends StatefulWidget {
  int index;
  ReviewListPage({Key? key,required this.index}) : super(key: key);

  @override
  _ReviewListPageState createState() => _ReviewListPageState();
}

class _ReviewListPageState extends State<ReviewListPage> with AutomaticKeepAliveClientMixin,RouteAware{
  /// 分页第一页页码
  static const int pageNumFirst = 1;
  /// 当前第几页
  int currentPageNum = pageNumFirst;
  /// 分页条目数量
  int pageSize = 20;
  /// 页面数据
  List list = [];
  ///状态
  int _status = LoadStatusType.loading;

  ///刷新组件
  RefreshController refreshController = RefreshController(initialRefresh: false);

  int get status => _status;

  set status(int value) {
    _status = value;
    setState(() {

    });
  }

  @override
  bool get wantKeepAlive => true;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    RouteUtils.routeObserver
        .subscribe(this, ModalRoute.of(context) as PageRoute);
  }

  @override
  void dispose() {
    RouteUtils.routeObserver.unsubscribe(this);
    super.dispose();
  }

  //回到当前页面
  @override
  void didPopNext() {
    refresh();
    print("审核返回刷新了---");
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    refresh();
  }

  //获取数据
  Future<List> loadData({int? pageNum}) async {
    //审核状态 1审核中 2已通过 3已驳回
    int status = 0;
    if(widget.index == 0){
      status = 0;
    }else if(widget.index == 1){
      status = 1;
    }else if(widget.index == 2){
      status = 3;
    }else if(widget.index == 3){
      status = 2;
    }
    return await ServiceRepository.specialAlbumList(page: pageNum!,pageSize: pageSize,status:status);
  }

  /// 下拉刷新
  ///
  /// [init] 是否是第一次加载
  /// true:  Error时,需要跳转页面
  /// false: Error时,不需要跳转页面,直接给出提示
  Future<List?> refresh({bool init = false}) async {
    try {
      currentPageNum = pageNumFirst;
      var data = await loadData(pageNum: pageNumFirst);
      if (data.isEmpty) {
        refreshController.refreshCompleted(resetFooterState: true);
        list.clear();
        status = LoadStatusType.empty;
      } else {
        list.clear();
        list.addAll(data);
        refreshController.refreshCompleted();
        // 小于分页的数量,禁止上拉加载更多
        if (data.length < pageSize) {
          refreshController.loadNoData();
        } else {
          //防止上次上拉加载更多失败,需要重置状态
          refreshController.loadComplete();
        }
        status = LoadStatusType.success;
      }
      return data;
    } catch (e, s) {
      /// 页面已经加载了数据,如果刷新报错,不应该直接跳转错误页面
      /// 而是显示之前的页面数据.给出错误提示
      if (init) list.clear();
      refreshController.refreshFailed();
      // setError(e, s);
      return null;
    }
  }

  /// 上拉加载更多
  Future<List?> loadMore() async {
    try {
      var data = await loadData(pageNum: ++currentPageNum);
      if (data.isEmpty) {
        currentPageNum--;
        refreshController.loadNoData();
      } else {
        list.addAll(data);
        if (data.length < pageSize) {
          refreshController.loadNoData();
        } else {
          refreshController.loadComplete();
        }
        setState(() {

        });
      }
      return data;
    } catch (e, s) {
      currentPageNum--;
      refreshController.loadFailed();
      return null;
    }
  }

  @override
  Widget build(BuildContext context) {
    return SmartRefresher(
      controller: refreshController,
      header: WaterDropHeader(),
      footer: ClassicFooter(),
      onRefresh: refresh,
      onLoading: loadMore,
      enablePullUp: true,
      child: Builder(
        builder: (context) {
          if(status != LoadStatusType.success){
            return StatusViews(status);
          }
          return ListView.builder(
            itemCount: list.length,
            itemBuilder: (context, int index) {
              AlbumListModel model = list[index];
              //审核状态 1审核中 2已通过 3已驳回
              //1 藏品 2专辑 3盲盒
              if(model.type == 2){
                if(model.specialAlbumStatus == 1){
                  return _reviewingWidget(model);
                }else if(model.specialAlbumStatus == 2){
                  return _revieSucceedWidget(model);
                }else{
                  return _revieFailureWidget(model);
                }
              }else{
                if(model.specialApplyStatus == 1){
                  return _reviewingWidget(model);
                }else if(model.specialApplyStatus == 2){
                  return _revieSucceedWidget(model);
                }else{
                  return _revieFailureWidget(model);
                }
              }
            },
          );
        }
      ),
    );
  }

  ///审核中
  Widget _reviewingWidget(AlbumListModel model){
    return Container(
      padding: EdgeInsets.only(left: 15,right: 15,top: 19,bottom: 16),
      decoration: BoxDecoration(
          border: Border(
            top: Divider.createBorderSide(context, width: 5),
          )
      ),
      child: Column(
        children: [
          ///订单信息
          orderInfoWidget(model),
          SizedBox(height: 11,),
          ///下单时间
          orderPriceWidget(time: model.createTime??"",name: "提交人:${model.nickname??""}"),
        ],
      ),
    );
  }
  ///审核失败
  Widget _revieFailureWidget(AlbumListModel model){
    return Container(
      padding: EdgeInsets.only(left: 15,right: 15,top: 19,bottom: 16),
      decoration: BoxDecoration(
          border: Border(
            top: Divider.createBorderSide(context, width: 5),
          )
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          ///订单信息
          orderInfoWidget(model),
          SizedBox(height: 11,),
          ///下单时间
          orderPriceWidget(time: model.createTime??"",name: "提交人:${model.nickname??""}"),
          SizedBox(height: 13,),
          orderMessageWidget(messaage: "失败原因：${model.specialAlbumReason??""}",color: Color(0xFFE02D2D)),
        ],
      ),
    );
  }

  ///审核成功
  Widget _revieSucceedWidget(AlbumListModel model){
    return Container(
      padding: EdgeInsets.only(left: 15,right: 15,top: 19,bottom: 16),
      decoration: BoxDecoration(
          border: Border(
            top: Divider.createBorderSide(context, width: 5),
          )
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          ///订单信息
          orderInfoWidget(model),
          SizedBox(height: 11,),
          ///下单时间
          orderPriceWidget(time: model.createTime??"",name: "提交人:${model.nickname??""}"),
          SizedBox(height: 13,),
          orderMessageWidget(messaage: "审核成功：审核通过的作品可以在我的-我创作的中发布上线售卖哦",color: Color(0xFF50E3C2)),
        ],
      ),
    );
  }

  ///订单信息
  Widget orderInfoWidget(AlbumListModel model){
    String image = "";
    String title = "";
    String project = "";
    String number = "";
    String state = "";
    //专辑
    if(model.type == 2){
      image = model.specialAlbumThumb??"";
      title = model.specialAlbumTitile??"";
      project = model.specialAlbumTitile??"";
      number = "版税金:${model.specialAlbumRate??""}%";
    }else if(model.type == 1){
      //1 藏品
      image = model.specialThumb??"";
      title = model.specialTitle??"";
      project = model.specialTypeName??"";
      number = "数量：${model.specialAllCount??""}";
    }else{
      //3盲盒
      image = model.specialThumb??"";
      title = model.specialTitle??"";
      project = model.specialTypeName??"";
      number = "数量：${model.specialAllCount??""}";
    }
    //1 藏品 2专辑 3盲盒
    if(model.type == 2) {
      //审核状态 1审核中 2已通过 3已驳回
      if (model.specialAlbumStatus == 1) {
        state = "审核中";
      } else if (model.specialAlbumStatus == 2) {
        state = "已通过";
      } else if (model.specialAlbumStatus == 3) {
        state = "已驳回";
      }
    }else{
      if(model.specialApplyStatus == 1){
        state = "审核中";
      }else if(model.specialApplyStatus == 2){
        state = "已通过";
      }else{
        state = "已驳回";
      }
    }
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        ClipRRect(borderRadius: BorderRadius.circular(8),child: LoadImage(image,
          fit: BoxFit.fitHeight,
          width: 80,height: 80,)),
        SizedBox(width: 13,),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(height: 2,),
            Text(title,style: TextStyle(fontSize: 14,color: Global.kTheme.textPrimary0,fontFamily: Global.mySemiboldFont,fontWeight:FontWeight.w600),),
            SizedBox(height: 9,),
            Text(project,style: TextStyle(fontSize: 14,color: Global.kTheme.inputHint1,fontFamily: Global.mySemiboldFont,fontWeight:FontWeight.w600),),
            SizedBox(height: 9,),
            Text(number,style: TextStyle(fontSize: 13,color: Global.kTheme.textPrimary0,fontFamily: Global.mySemiboldFont,fontWeight:FontWeight.w600),),
          ],
        ),
        Spacer(),
        Text(state,textAlign: TextAlign.end, style: TextStyle(fontSize: 12,color: Global.kTheme.inputHint1,),)
      ],
    );
  }

  ///提交时间
  Widget orderPriceWidget({required String time,required String name}){
    return Row(
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        Text("提交时间:",style: TextStyle(fontSize: 12,color: Global.kTheme.inputHint1),),
        Text(time,style: TextStyle(fontSize: 12,color: Global.kTheme.inputHint1),),
        Spacer(),
        Expanded(child: Text(name,maxLines: 1,overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 14,color: Global.kTheme.textPrimary4,fontFamily: Global.mySemiboldFont),)),
        SizedBox(width: 5,)
      ],
    );
  }

  ///描述信息
  Widget orderMessageWidget({required String messaage,required Color color}){
    return Container(
      child: Text(messaage,textAlign: TextAlign.start ,style: TextStyle(fontSize: 12,color: color),),
    );
  }

}
